﻿namespace UnityEditor
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Text.RegularExpressions;
    using UnityEditorInternal;
    using UnityEngine;

    internal sealed class AssetStoreContext : ScriptableObject
    {
        public bool docked;
        private static Regex generatedIDRe = new Regex(@"^\{(.*)\}$");
        public string initialOpenURL;
        private static Regex invalidPathChars = new Regex("[^a-zA-Z0-9() _-]");
        private static Regex standardPackageRe = new Regex(@"/Standard Packages/(Character\ Controller|Glass\ Refraction\ \(Pro\ Only\)|Image\ Effects\ \(Pro\ Only\)|Light\ Cookies|Light\ Flares|Particles|Physic\ Materials|Projectors|Scripts|Standard\ Assets\ \(Mobile\)|Skyboxes|Terrain\ Assets|Toon\ Shading|Tree\ Creator|Water\ \(Basic\)|Water\ \(Pro\ Only\))\.unitypackage$", RegexOptions.IgnoreCase);
        public AssetStoreWindow window;

        private AssetStoreContext()
        {
        }

        private void ContextMenuClick(object userData, string[] options, int selected)
        {
            if (selected >= 0)
            {
                string[] strArray = userData as string[];
                this.JS.EvalJavaScript(strArray[selected]);
            }
        }

        public void DeleteKey(string key)
        {
            EditorPrefs.DeleteKey(key);
        }

        public void Download(WebScriptObject package, WebScriptObject downloadInfo)
        {
            string url = (string) downloadInfo.Get("url");
            string key = (string) downloadInfo.Get("key");
            string str3 = (string) downloadInfo.Get("id");
            string str4 = (string) package.Get("title");
            string str5 = (string) package.Get("publisher.label");
            string str6 = (string) package.Get("category.label");
            Download(str3, url, key, str4, str5, str6, null);
        }

        public static void Download(string package_id, string url, string key, string package_name, string publisher_name, string category_name, AssetStoreUtils.DownloadDoneCallback doneCallback)
        {
            string[] destination = PackageStorePath(publisher_name, category_name, package_name, package_id, url);
            JSONValue value2 = JSONParser.SimpleParse(AssetStoreUtils.CheckDownload(package_id, url, destination, key));
            if (value2.Get("in_progress").AsBool(true))
            {
                Debug.Log("Will not download " + package_name + ". Download is already in progress.");
            }
            else
            {
                string str = value2.Get("download.url").AsString(true);
                string str2 = value2.Get("download.key").AsString(true);
                bool resumeOK = (str == url) && (str2 == key);
                JSONValue value3 = new JSONValue();
                value3["url"] = url;
                value3["key"] = key;
                JSONValue value4 = new JSONValue();
                value4["download"] = value3;
                AssetStoreUtils.Download(package_id, url, destination, key, value4.ToString(), resumeOK, doneCallback);
            }
        }

        public string GetAuthToken()
        {
            return InternalEditorUtility.GetAuthToken();
        }

        public bool GetDockedStatus()
        {
            return this.docked;
        }

        public float GetFloat(string key)
        {
            return EditorPrefs.GetFloat(key);
        }

        public string GetInitialOpenURL()
        {
            if (this.initialOpenURL != null)
            {
                string initialOpenURL = this.initialOpenURL;
                this.initialOpenURL = null;
                return initialOpenURL;
            }
            return string.Empty;
        }

        public int GetInt(string key)
        {
            return EditorPrefs.GetInt(key);
        }

        public int[] GetLicenseFlags()
        {
            return InternalEditorUtility.GetLicenseFlags();
        }

        public WebScriptObject GetPackageList()
        {
            Dictionary<string, WebScriptObject> dictionary = new Dictionary<string, WebScriptObject>();
            WebScriptObject obj2 = this.JS.ParseJSON("{}");
            WebScriptObject obj3 = this.JS.ParseJSON("[]");
            foreach (PackageInfo info in PackageInfo.GetPackageList())
            {
                WebScriptObject obj4;
                if (info.jsonInfo == string.Empty)
                {
                    obj4 = this.JS.ParseJSON("{}");
                    obj4.Set<string>("title", Path.GetFileNameWithoutExtension(info.packagePath));
                    obj4.Set<string>("id", "{" + info.packagePath + "}");
                    if (this.IsBuiltinStandardAsset(info.packagePath))
                    {
                        obj4.Set<WebScriptObject>("publisher", this.JS.ParseJSON("{\"label\": \"Unity Technologies\",\"id\": \"1\"}"));
                        obj4.Set<WebScriptObject>("category", this.JS.ParseJSON("{\"label\": \"Prefab Packages\",\"id\": \"4\"}"));
                        obj4.Set<string>("version", "3.5.0.0");
                        obj4.Set<string>("version_id", "-1");
                    }
                }
                else
                {
                    obj4 = this.JS.ParseJSON(info.jsonInfo);
                    if (obj4.Get("id") == null)
                    {
                        WebScriptObject obj5 = obj4.Get("link");
                        if (obj5 != null)
                        {
                            obj4.Set<string>("id", (string) obj5.Get("id"));
                        }
                        else
                        {
                            obj4.Set<string>("id", "{" + info.packagePath + "}");
                        }
                    }
                }
                string key = (string) obj4.Get("id");
                obj4.Set<string>("local_icon", info.iconURL);
                obj4.Set<string>("local_path", info.packagePath);
                if ((!dictionary.ContainsKey(key) || (dictionary[key].Get("version_id") == null)) || ((obj4.Get("version_id") != null) && (dictionary[key].Get("version_id") <= obj4.Get("version_id"))))
                {
                    dictionary[key] = obj4;
                }
            }
            int num2 = 0;
            foreach (KeyValuePair<string, WebScriptObject> pair in dictionary)
            {
                obj3.Set<WebScriptObject>(num2++, pair.Value);
            }
            obj2.Set<WebScriptObject>("results", obj3);
            return obj2;
        }

        public int GetSkinIndex()
        {
            return EditorGUIUtility.skinIndex;
        }

        public string GetString(string key)
        {
            return EditorPrefs.GetString(key);
        }

        public bool HasKey(string key)
        {
            return EditorPrefs.HasKey(key);
        }

        private bool IsBuiltinStandardAsset(string path)
        {
            return standardPackageRe.IsMatch(path);
        }

        public void MakeMenu(WebScriptObject contextMenu)
        {
            this.MakeMenu(contextMenu, 0f, 0f);
        }

        public void MakeMenu(WebScriptObject contextMenu, float deltaX, float deltaY)
        {
            WebScriptObject obj2 = contextMenu.Get("commands");
            int num = (int) obj2.Get("length");
            string[] options = new string[num];
            string[] userData = new string[num];
            for (int i = 0; i < obj2.Get("length"); i++)
            {
                WebScriptObject obj3 = obj2.Get(i);
                options[i] = (string) obj3.Get("label");
                userData[i] = (string) obj3.Get("action");
            }
            Vector2 mousePosition = Event.current.mousePosition;
            Rect position = new Rect(mousePosition.x + deltaX, mousePosition.y + deltaY, 0f, 0f);
            EditorUtility.DisplayCustomMenu(position, options, null, new EditorUtility.SelectMenuItemFunction(this.ContextMenuClick), userData);
        }

        public void OpenBrowser(string url)
        {
            Application.OpenURL(url);
        }

        public bool OpenPackage(string id)
        {
            return this.OpenPackage(id, "default");
        }

        public bool OpenPackage(string id, string action)
        {
            return OpenPackageInternal(id);
        }

        public static bool OpenPackageInternal(string id)
        {
            Match match = generatedIDRe.Match(id);
            if (match.Success && File.Exists(match.Groups[1].Value))
            {
                AssetDatabase.ImportPackage(match.Groups[1].Value, true);
                return true;
            }
            foreach (PackageInfo info in PackageInfo.GetPackageList())
            {
                if (info.jsonInfo != string.Empty)
                {
                    JSONValue value2 = JSONParser.SimpleParse(info.jsonInfo);
                    string str = !value2.Get("id").IsNull() ? value2["id"].AsString(true) : null;
                    if (((str != null) && (str == id)) && File.Exists(info.packagePath))
                    {
                        AssetDatabase.ImportPackage(info.packagePath, true);
                        return true;
                    }
                }
            }
            Debug.LogError("Unknown package ID " + id);
            return false;
        }

        public static string[] PackageStorePath(string publisher_name, string category_name, string package_name, string package_id, string url)
        {
            string[] strArray = new string[] { publisher_name, category_name, package_name };
            for (int i = 0; i < 3; i++)
            {
                strArray[i] = invalidPathChars.Replace(strArray[i], string.Empty);
            }
            if (strArray[2] == string.Empty)
            {
                strArray[2] = invalidPathChars.Replace(package_id, string.Empty);
            }
            if (strArray[2] == string.Empty)
            {
                strArray[2] = invalidPathChars.Replace(url, string.Empty);
            }
            return strArray;
        }

        [MethodImpl(MethodImplOptions.InternalCall), WrapperlessIcall]
        public static extern string SessionGetString(string key);
        [MethodImpl(MethodImplOptions.InternalCall), WrapperlessIcall]
        public static extern bool SessionHasString(string key);
        [MethodImpl(MethodImplOptions.InternalCall), WrapperlessIcall]
        public static extern void SessionRemoveString(string key);
        [MethodImpl(MethodImplOptions.InternalCall), WrapperlessIcall]
        public static extern void SessionSetString(string key, string value);
        public void SetFloat(string key, float value)
        {
            EditorPrefs.SetFloat(key, value);
        }

        public void SetInt(string key, int value)
        {
            EditorPrefs.SetInt(key, value);
        }

        public void SetString(string key, string value)
        {
            EditorPrefs.SetString(key, value);
        }

        private WebScriptObject JS
        {
            get
            {
                return this.window.scriptObject;
            }
        }

        public WebScriptObject packages
        {
            get
            {
                return this.GetPackageList().Get("results");
            }
        }
    }
}

